package com.mew.auc.service;

import com.mew.auc.provide.RegisterFeignService;
import com.mew.common.dc.db.LoginoutService;
import com.mew.common.dc.db.ProfileService;
import com.mew.common.dc.db.UserService;
import com.mew.common.dc.mapper.EventsMapper;
import com.mew.common.dc.redis.AucRedisService;
import com.mew.common.enm.UserLoginType;
import com.mew.common.enm.UserType;
import com.mew.common.entity.events.Events;
import com.mew.common.entity.user.Profile;
import com.mew.common.entity.user.User;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.bo.MewSession;
import com.mew.common.rest.login.ForcedOfflineRequest;
import com.mew.common.rest.login.LoginGuestRequestMessage;
import com.mew.common.rest.login.LoginResponseMessage;
import com.mew.common.util.RandomIdUtil;
import com.mew.auc.config.LobbyUserConfig;
import com.zebra.common.OnlineType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Date 2020/11/7 0007
 **/
@Service
@Slf4j
public class LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private ProfileService profileService;
    @Autowired
    private LoginoutService loginoutService;
    @Autowired
    private AucRedisService aucRedisService;
    @Autowired
    private LobbyUserConfig lobbyConfig;
    @Autowired
    private EventsMapper eventsMapper;
    @Autowired
    private RegisterFeignService registerFeignService;


    //如果 传了 uid 则就用uid 登录；
    public LoginResponseMessage guestLogin(LoginGuestRequestMessage loginRequestVO){
        User user = null;
        if (loginRequestVO.getUid() > 0){
            user = userService.getUserById(loginRequestVO.getUid());
            if (null == user){
                return new LoginResponseMessage().buildByResponseCode(ResponseCode.UserNotInfo);
            }

        }else if (StringUtils.isNotEmpty(loginRequestVO.getMac())){
            user = userService.getUserByLoginType(loginRequestVO.getMac(), UserLoginType.MAC);
            if (null != user && user.getId() == null){
                return new LoginResponseMessage().buildByResponseCode(ResponseCode.UserTelRepeat);
            }
        }

        Profile profile;
        if (null == user){
            String newMac = StringUtils.isNotEmpty(loginRequestVO.getMac()) ? loginRequestVO.getMac() : "Mac_"+ RandomIdUtil.generateString(12);
            user = registerGuestUser(loginRequestVO, newMac);
            profile = profileService.createProfile(user.getId(), lobbyConfig.getRegisterNumber());
            Events events = new Events();
            events.setUserId(user.getId());
            eventsMapper.insert(events);
        }else {
            profile = profileService.getProfileById(user.getId());
            if (null == profile){
                return new LoginResponseMessage().buildByResponseCode(ResponseCode.UserErrorInfo);
            }
        }

        MewSession session = doLogin(user.getId(), loginRequestVO.getMac(), loginRequestVO.getIp(), loginRequestVO.getDevicesType());
        return LoginResponseMessage.builder().build().buildData(user, profile, session);
    }

    private User registerGuestUser(LoginGuestRequestMessage requestVO, String newMac){
        User requestUser = new User();
        requestUser.setAddMac(newMac);
        Optional.ofNullable(requestVO.getIp()).ifPresent(ip -> requestUser.setAddIp(ip));
        requestUser.setUserType(UserType.Common.code());
        return userService.createUser(requestUser, lobbyConfig.getGidStart(), lobbyConfig.getGidLen());
    }

    public MewSession doLogin(long userId, String mac, String ip, int devType){
        MewSession session = aucRedisService.getSession(userId);

        if (null != session && OnlineType.Online.value() == session.onl){
            registerFeignService.forcedOffline(ForcedOfflineRequest.builder()
                    .gatewaySid(session.gwsid)
                    .userId(session.uid)
                    .token(session.tk)
                    .build());
        }
        return loginoutService.login(session, userId, mac, ip, devType);
    }




}
